<?php
    /*

     Version: MPL 1.1

     Software distributed under the License is distributed on an "AS IS"
     basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     License for the specific language governing rights and limitations
     under the License.

     The Original Code is KASSIOP Framework.

     The Initial Developer of the Original Code is SURIAN Nicolas (aka NairuS) <me@nairus.fr>.
     Portions created by the Initial Developer are Copyright (C) 2010
     The Initial Developer. All Rights Reserved.

     Contributor(s):

     Alternatively, the contents of this file may be used under the terms
     of the MPL license Version 1.1 (the  "MPL" License"), in which case the
     provisions of Version: MPL 1.1 License are applicable instead of those
     above.  If you wish to allow use of your version of this file only
     under the terms of the MPL License and not to allow others to use
     your version of this file under the MPL, indicate your decision by
     deleting  the provisions above and replace  them with the notice and
     other provisions required by the MPL License.  If you do not delete
     the provisions above, a recipient may use your version of this file
     under either the MPL License.

     The contents of this file are subject to the Mozilla Public License
     Version 1.1 (the "License"); you may not use this file except in
     compliance with the License. You may obtain a copy of the License at
     http://www.mozilla.org/MPL/

    */

    /**
     * Defines the model to validate.
     *
     * @package    kassiop.core
     * @subpackage models
     *
     * @author NairuS
     */
    abstract class Model implements iValidate, Serializable
    {
        /**
         * Create an instance of Model
         */
        public function __construct( ValueObject $vo )
        {
            $this->setExcludeFields( array( Model::EXPLICIT_TYPE ) ) ;
            $this->vo = $vo ;
            $this->configure() ;
        }

        const ID_FIELD      = 'id' ;
        const EXPLICIT_TYPE = '_explicitType' ;

        /**
         * Defines the errors serialized.
         *
         * @var string
         */
        public $serialized ;

        /**
         * The vo of the model to validate.
         *
         * @var ValueObject
         */
        public $vo ;

        /**
         * Defines the errors of the model validation.
         *
         * @var array
         */
        private $errors = array() ;

        /**
         * Excludes some model fields of the validation.
         *
         * @var array
         */
        private $excludeFields = array() ;

        /**
         * Defines the postValidators of the model
         *
         * @var array
         */
        private $postValidators = array() ;

        /**
         * Defines the validators of the model
         *
         * @var array
         */
        private $validators = array() ;

        /**
         * (non-PHPdoc)
         * @see kassiop/core/models/iValidable#hasErrors()
         */
        public function hasErrors()
        {
            return count( $this->getErrors() ) > 0 ;
        }

        /**
         * Returns all the errors of the model.
         *
         * @return array
         */
        public function getErrors()
        {
            return $this->errors ;
        }

        /**
         * Returns an ErrorVO of the model.
         *
         * @param  string  $name
         * @return ErrorVO
         */
        public function getError( $name )
        {
            if( $this->hasErrors() )
            {
                foreach( $this->getErrors() as $e )
                {
                    if( $e instanceof ErrorVO && $e->field == $name)
                    {
                        return $e ;
                    }
                }
            }
            return null;
        }

        /**
         * Returns the excludeFields array.
         *
         * @return array
         */
        public function getExcludeFields()
        {
            return $this->excludeFields ;
        }

        /**
         * Returns the all the validators of the model.
         *
         * @return array
         */
        public function getPostValidators()
        {
            return $this->postValidators ;
        }

        /**
         * Returns the validator for the field passed-in.
         *
         * @param string $field
         * @return BaseValidator
         */
        public function getPostValidator( $field )
        {
            return isset( $this->postValidators[$field] ) && $this->postValidators[$field] instanceof BaseValidator ? $this->postValidators[$field] : null ;
        }

        /**
         * Returns the validator for the field passed-in.
         *
         * @param string $field
         * @return BaseValidator
         */
        public function getValidator( $field )
        {
            return isset( $this->validators[$field] ) && $this->validators[$field] instanceof BaseValidator ? $this->validators[$field] : null ;
        }

        /**
         * Returns the all the validators of the model.
         *
         * @return array
         */
        public function getValidators()
        {
            return $this->validators ;
        }

        /**
         * Merges the excludeFields array.
         *
         * @param  $fields
         * @return void
         */
        public function setExcludeFields( array $fields )
        {
            $this->excludeFields = array_merge( $this->excludeFields, $fields ) ;
        }

        /**
         * Sets a postValidator for a field in the collection.
         *
         * @param  string        $field
         * @param  BaseValidator $validator
         * @return void
         */
        public function setPostValidator( $field, BaseValidator $validator )
        {
            $this->postValidators[$field] = $validator ;
        }

        /**
         * Sets all the validators of the model.
         *
         * @param array $validators
         */
        public function setPostValidators( array $validators )
        {
            $this->postValidators = $validators ;
        }

        /**
         * Sets the validator for the field passed-in.
         *
         * @param  string        $field
         * @param  BaseValidator $validator
         * @return void
         */
        public function setValidator( $field, BaseValidator $validator )
        {
            $this->validators[$field] = $validator ;
        }

        /**
         * Sets all the validators of the model.
         *
         * @param array $validators
         */
        public function setValidators( array $validators )
        {
            $this->validators = $validators ;
        }

        /**
         * Serializes the errors of the model.
         *
         * @return string of the model's errors serialized.
         */
        public function serialize()
        {
            return $this->serialized = serialize( $this->getErrors() ) ;
        }

        /**
         * Unserializes the errors of the model.
         *
         * @return array of the model's errors unserialized.
         */
        public function unserialize( $serialized )
        {
            return unserialize( $serialized );
        }

        /**
         * Validates all the model fields.
         *
         * @see kassiop/core/models/iValidable#validate()
         * @return true or false.
         */
        public function validate()
        {
            $reflection = new ReflectionClass( $this->vo ) ;
            foreach( $reflection->getProperties() as $prop )
            {
                $propName = $prop->name ;

                // launch all the validators.
                if( !in_array( $propName, $this->getExcludeFields() ) )
                {
                    try
                    {
                        // try the validator of the property.
                        $validator = $this->getValidator( $propName ) ;
                        if( $validator instanceof BaseValidator )
                        {
                            $this->vo->$propName = $validator->clean( $this->vo->$propName );

                            // try the post validator if it exists.
                            $postValidator = $this->getPostValidator( $propName ) ;
                            if( $postValidator instanceof BaseValidator )
                            {
                                $this->vo->$propName = $postValidator->clean( $this->vo->$propName );
                            }
                        }
                        else
                        {
                            $init = array(
                                'field'   => $propName,
                                'message' => 'The field "' . $propName . '" has no validator setted!'
                            ) ;
                            $this->errors[] = new ErrorVO( $init ) ;
                        }
                    }
                    catch( ErrorBaseValidator $e )
                    {
                        $init = array(
                            'field'   => $propName,
                            'message' => $e->getMessage()
                        ) ;
                        $this->errors[] = new ErrorVO( $init ) ;
                    }
                }
            }

            return $this->hasErrors() === false ;
        }

        /**
         * Configure the validation of this model.
         *
         * @param array $exludeFields
         * @return void
         */
        protected function configure( $exludeFields = array() )
        {
            if( !empty( $exludeFields ) )
            {
                $this->setExcludeFields( $exludeFields ) ;
            }
            $this->setValidator( self::ID_FIELD, new IntegerValidator( array( IntegerValidator::$minKey => 1 ) ) ) ;
        }
    }
?>